// miniprogram/pages/work_log/show.js
var util = require('../util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    load: true,//加载
    showit: true,//查看
    wtitle: '',
    Delfiles: [],
    Delyun: [],
    imagesList: [],
    fileIDs: [], //上传云存储后的返回值
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.edit);
    if (options.edit) {
      this.setData({
        showit: false,
        id:options.id
      })
    }

    wx.showLoading({
      title: '正在加载数据',
    })
    this.getinfo(options);
  },

  getinfo: function (options) {
    let id = options.id;
    let that = this, data = '{"[]":{"K_W_Record":{"id":"' + id + '"},"K_W_Photo[]":{"K_W_Photo":{"Pid@":"/K_W_Record/Pid","@column": "Memo:image,id:[index]"}}}}';
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data
      },
      success: res => {
        //console.log(res.result);
        let obj = JSON.parse(res.result)["[]"];
        if (obj.length == 0) {
          wx.showToast({
            icon: 'none',
            title: '当前没有数据',
          })
          return;
        }
        var K_W_Record = obj[0]["K_W_Record"]//基础资料
        var K_W_Photo = obj[0]["K_W_Photo[]"]//图片资料K_W_Photo.length       
        that.setData({
          guid: K_W_Record.Pid,
          wtitle: K_W_Record.Name,
          attributeValue0:K_W_Record.attributeValue0,
          currentText: K_W_Record.Memo,
          CreateDate: K_W_Record.CreateDate,
          imagesYun: K_W_Photo,
          load: false
        })
        wx.hideLoading({
          complete: (res) => { },
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })

  },
  //图片
  chooseImage(e) {
    var that = this
    var imgs = that.data.imagesList;
    if (imgs.length > 4) {
      wx.showToast({
        icon: 'none',
        title: '减少资源浪费，最多只能上传3张图片',
      })
      return false;
    };
    wx.chooseImage({
      count: (5 - imgs.length), // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: [ 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = imgs.concat(res.tempFilePaths);
        that.setData({
          imagesList: tempFilePaths
        })
        //console.log(that.data.imagesList)
      }
    })
  },
  showiewImage: function (e) {//云图片
    var current = e.currentTarget.dataset.id;
    wx.previewImage({
      urls: ["cloud:///img/" + current] // 需要预览的图片http链接列表  
    })
  },
  deleteShow: function (e) {//云图片  
    var imgs = this.data.imagesYun,
      index = e.currentTarget.dataset.idx,
      Delid = e.currentTarget.dataset.id,
      Delfile = "cloud:///img/" + e.currentTarget.dataset.file;
    imgs.splice(index, 1);
    this.setData({
      imagesYun: imgs,
      Delyun: this.data.Delyun.concat(Delid),
      Delfiles: this.data.Delyun.concat(Delfile),
    });
  },
  previewImage: function (e) {
    var current = e.currentTarget.dataset.id;
    console.log(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.imagesList // 需要预览的图片http链接列表  
    })
  },
  deleteImg: function (e) {
    var imgs = this.data.imagesList;
    var index = e.currentTarget.dataset.idx;
    imgs.splice(index, 1);
    this.setData({
      imagesList: imgs
    });
  },
  onBack: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  formSubmit: function (e) {    
    var that = this;
    let {
      caption,
      currentText
    } = e.detail.value;
    if (!currentText) {
      wx.showToast({
        icon: 'none',
        title: '请输入相关信息！',
      });
      return;
    }
    wx.showLoading(); //展示加载
    let promiseArr = [];
    var imgs = this.data.imagesList,
      guid = this.data.guid,
      imagesYun=this.data.imagesYun,
      Delyun = this.data.Delyun,
      Delfil = this.data.Delfiles;
    console.log(Delfil.length);
    if (Delfil.length > 0) {//删除文件
      wx.cloud.deleteFile({
        fileList: Delfil
      })
      for (let i = 0; i < Delyun.length; i++) {
        let data = '{"K_W_Photo": { "id": "' + Delyun[i] + '"}}';
        util.Yun_del(data);
      }
    }
    if (imgs.length > 0) {//上传图片
      for (let i = 0; i < imgs.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          //------------------------------
          let filePath = this.data.imagesList[i];
          let fileName = guid + "-" + (i + imagesYun.length) + filePath.match(/\.[^.]+?$/)[0]
          let cloudPath = "img/" + fileName;
          wx.cloud.uploadFile({
            cloudPath, //云存储图片名字
            filePath, //临时路径
            success: res => {
              console.log('[上传图片] 成功：', res)
              this.setData({
                fileIDs: this.data.fileIDs.concat(fileName)
              });
              let data = '{"K_W_Photo": {"Openid":"' + getApp().globalData.openid + '","Name":"' + getApp().globalData.name + '","Creatorid":"' + getApp().globalData.appid + '","Memo":"' + fileName + '","pid":"' + guid +'","attributeValue0":"'+caption+ '","TypeName":"photo"}}';
              console.log(data);
              util.Yun_add(util.encode(util.encodeUTF8(data)));
            },
            fail: res => {
              console.error('[上传图片] 失败：', res)
            },
            complete: res => {
              reslove();
            }
          });
          //------------------------------
        }));
      }
    }
    
    Promise.all(promiseArr).then(res => { //等数组都做完后做then方法     
      let data = '{"K_W_Record": {"id":"' + this.data.id + '","Rid":"' + (imgs.length+imagesYun.length) +'","Memo":"' + currentText+'","DataLevel":0}}';
      console.log(data);
      util.Yun_eidt(util.encode(util.encodeUTF8(data)));
      wx.hideLoading();
    })
    wx.showModal({
      title: '提交成功',
      content: '是否返回主界面？',
      success(res) {
        if (res.confirm) {
          wx.redirectTo({
            url: '../console/Index',
          })
        }else{          
          wx.redirectTo({
            url: 'List',
          })
        }
      }
    })
  },
})